package com.ct.gd.passport.view.policy;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.View;
import android.widget.ListView;

import com.ct.gd.passport.domain.PolicyCatalog;
import com.ct.gd.passport.view.BundleKeys;
import com.up91.common.android.view.adapter.SimpleListAdapter;

public class PolicyCatalogSearchFragment extends AbsPolicyCatalogFragment {

	private LoaderManager	loaderManager;
	private String			keyword;

	@Override
	protected SimpleListAdapter<PolicyCatalog> onInitListAdapter() {
		return new PolicyCatalogListAdapter(getActivity(), null);
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		PolicyCatalog info = (PolicyCatalog) l.getItemAtPosition(position);

		// enter detail
		Intent intent = new Intent(this.getActivity(), PolicyDetailActivity.class);
		intent.putExtra(BundleKeys.CATALOG_ID, info.getCatalogId());
		startActivity(intent);
	}

	public void search(String keyword) {
		this.keyword = keyword;
		loadCatalog();
	}

	protected void loadCatalog() {
		load(getCatalogLoader());
	}

	protected PolicyCatalogLoader getCatalogLoader() {
		loaderManager = getActivity().getSupportLoaderManager();
		Loader<List<PolicyCatalog>> loader = loaderManager.getLoader(0);
		if (null == loader) loader = loaderManager.initLoader(0, null, this);
		return (PolicyCatalogLoader) loader;
	}

	@Override
	protected void load(PolicyCatalogLoader loader) {
		((PolicyCatalogSearchLoader)loader).setKeyword(keyword);
		loader.reset();
		loader.startLoading();
	}

	@Override
	public Loader<List<PolicyCatalog>> onCreateLoader(int id, Bundle args) {
		return new PolicyCatalogSearchLoader(getActivity(), getListView());
	}
	
}
